import axios from 'axios';
import { useRouter } from "vue-router";

// create an axios instance
const instance = axios.create({
  baseURL: '/hramis',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 100000,
});

// request interceptor
instance.interceptors.request.use(
  (config) => {

    const token = localStorage.getItem("token");
    if (token) {
      config.headers.common['authorization'] = token;
    }

    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// response interceptor
instance.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;    
    console.log(res, "res")
    if (res.status === -2) {
      localStorage.removeItem("token");
      // const router = useRouter()
      // router.push("/login");
      location.href = "/login"
      return Promise.reject("登录异常");
    }
    return res;
  },
  (error) => {
    return Promise.reject(error.message);
  },
);

/**
 * reactive useFetchApi
 */

export default instance;
